// pages/mqttTest/mqttTest.js
var mqtt = require('../../utils/mqtt.js');
//一个全局变量...
var client = null;
//一个全局变量...
let socketOpen = false
Page({
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
      this.connectMqtt();
  },
  connectMqtt: function () {
    const options = {
      connectTimeout: 4000, // 超时时间
      clientId: 'wx_' + parseInt(Math.random() * 100 + 800, 10),
      port: 8083, //重点注意这个,坑了我很久,一定是8083不是1883也不是443
      // username: 'xxx',
      // password: 'xxx',
    }

    client = mqtt.connect('wx://8.136.195.245/mqtt', options)
    client.on('reconnect', (error) => {
      console.log('正在重连:', error)
    })

    client.on('error', (error) => {
      console.log('连接失败:', error)
    })

    let that = this;
    client.on('connect', (e) => {
      console.log('成功连接服务器')
      //订阅一个主题
      client.subscribe('message.queue', {
        qos: 0
      }, function (err) {
        if (!err) {
          console.log("订阅成功")
        }
      })
    })
    client.on('message', function (topic, message) {
      console.log('received msg:' + message.toString());
    })
    client.publish('message.queue', 'Hello MQTT')
  }


})
